package com.netty.clientserver.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.netty.clientserver.packet.Register;
import com.netty.clientserver.packet.base.Packet;
import com.netty.clientserver.packet.bo.RegisterBo;
import com.netty.clientserver.strategy.TypeStrategy;
import com.netty.clientserver.util.TokenUtil;
import com.netty.common.entity.User;
import com.netty.common.entity.vo.LoginUser;
import com.netty.common.enums.ExceptionEnum;
import com.netty.common.enums.TypeEnum;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Objects;

/** 注册
 * @author LiuXiaoYu
 * @date 2022/2/3- 14:23
 */
@Component("7")
public class RegisterTypeStrategyImpl implements TypeStrategy {

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public Packet execute(Channel channel, String type, String content) {
        RegisterBo registerBo = JSONObject.parseObject(content,new TypeReference<RegisterBo>(){});
        //取出Json对象中的属性
        String token = registerBo.getToken();
        //从redis缓存中获取token并根据token获取登录的用户token信息
        LoginUser loginUser = tokenUtil.getLoginUser(token);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException(ExceptionEnum.NEED_LOGIN.getDesc());
        }
        //校验token是否需要刷新延长时间
        tokenUtil.verifyToken(loginUser);
        User user = loginUser.getUser();
        Register register=new Register();
        register.setGroupChannel(registerBo.getGroupChannel());
        register.setUser(user);
        register.setToId(registerBo.getToId());
        return register;
    }
}
